/* Copyright (c) 2016-2020 Enfry Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Enfry. 
 * You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with Enfry.
 */
package com.enfry.common.util.httpclient;

import java.io.IOException;
import java.net.HttpURLConnection;

import com.enfry.common.util.validate.Validates;

/**
 * HTTP/HTTPS POST访问类 1.内容以字符串为主，在写入时根据编码格式转换成字节 2.当内容不为空时，必须有mimeType和encoding值
 * 
 * @Title com.enfry.util.httpclient.HttpPost
 * @author Penghu
 * @date 2016年11月10日
 */
public class HttpPost extends HttpClient {
	private String queryString;
	private String mimeType;
	private String encoding;

	public HttpPost(String url) {
		super(url, _POST_);

		this.mimeType = _APPLICATION_X_WWW_FORM_;
		this.encoding = _UTF_8_;
	}

	public void setQueryString(String queryString, String encoding) {
		this.queryString = queryString.trim();
		this.encoding = encoding.trim();
	}

	public void setQueryString(String queryString, String mimeType, String encoding) {
		this.queryString = queryString;
		this.mimeType = mimeType;
		this.encoding = encoding;
	}

	@Override
	protected boolean doPreRequestProperty() {
		if (Validates.isEmpty(queryString)) {
			return true;
		}

		setDoOutput(true);
		addRequestProperty(_CONTENT_TYPE_, mimeType + "; charset=" + encoding);
		addRequestProperty(_CONTENT_LENGTH_, "" + queryString.getBytes().length);
		return true;
	}

	protected void doWriteRequestContent(HttpURLConnection conn) throws IOException {
		if (Validates.isEmpty(queryString))
			return;

		conn.getOutputStream().write(queryString.getBytes(encoding));
	}

	public void setMimeType(String mimeType) {
		this.mimeType = mimeType;
	}
}
